package com.sooncode.project.focusservice.service;

import com.sooncode.project.core.finder.Finder;
import com.sooncode.project.core.finder.Page;
import com.sooncode.project.core.finder.Sort;
import com.sooncode.project.core.model.DomainException;
import com.sooncode.project.core.session.DomainSession;
import com.sooncode.project.focusservice._.request.OrgSyncClient;
import com.sooncode.project.focusservice._.request.UserClient;
import com.sooncode.project.focusservice.model.DeviceLogin;
import com.sooncode.project.focusservice.model.Organization;
import com.sooncode.project.focusservice.model.OrganizationType;
import com.sooncode.project.springcloudcommon.model.AuthInfo;
import com.sooncode.project.springcloudcommon.utils.UserUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class OrganizationService {
    @Autowired
    UserClient userClient;
    @Autowired
    OrgSyncClient orgSyncClient;

    public boolean add(Map map) {
        Organization org = new Organization();
        org.add(map, userClient, orgSyncClient);
        return true;
    }

    public boolean modify(String id, Map map) {
        Organization org = findById(id);
        org.modify(map);
        return true;
    }

    public boolean delete(String id) {
        Organization org = findById(id);
        org.delete();
        return true;
    }

    public List<Map> getDeviceMacs(String id) {
        Organization org = findById(id);
        List<Map> result = new ArrayList<>();
        if(org.getDeviceMac() == null)
            return result;
        for (Map.Entry<String, String> entry : org.getDeviceMac().entrySet()) {
            Map m = new HashMap();
            m.put("mac", entry.getKey());
            m.put("status", entry.getValue());
            result.add(m);
        }
        return result;
    }

    public Page<DeviceLogin> getLoginList(String id, int pageSize, int pageIndex, Map where) {
        if (StringUtils.isEmpty(id)) {
            throw new RuntimeException("参数错误");
        }
        return new Finder<>(DeviceLogin.class)
            .byField("orgId", id)
            .and(where)
            .page(pageSize, pageIndex, Sort.DESC("loginDate"));
    }

    public Map login(Map params) {
        String userName = params.get("account").toString();
        String password = params.get("password").toString();
        String mac = params.get("mac").toString();
        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password) || StringUtils.isEmpty(mac)) {
            throw new RuntimeException("参数错误");
        }
        Organization org = new Finder<>(Organization.class)
            .byField("managerPhone", userName).first();
        DomainSession session = new DomainSession();
        session.add(org);
        if (!org.getDevicePassword().matches(password)) {
            throw new DomainException("密码错误");
        }
        Map loginMap = userClient.loginById(org.getAccountId());
        String accountId = loginMap.get("id").toString();
        try {
            if (org.getDeviceMac() == null || !org.getDeviceMac().containsKey(mac)) {
                org.addDevice(mac);
            }
            DeviceLogin dl = new DeviceLogin();
            dl.setLoginDate(new Date());
            dl.setOrgId(org.getId());
            dl.setDeviceMac(mac);
            dl.add();
            session.add(dl);
            session.commit();
        } catch (Exception ex) {
            session.rollback();
            throw ex;
        }
        Map result = new HashMap();
        result.put("userId", accountId);
        result.put("name", loginMap.get("realName"));
        result.put("jwt", loginMap.get("jwt"));
        return result;
    }

    public Page<Organization> getPageList(int pageSize, int pageIndex, Map map) {
        Page<Organization> result = new Finder<>(Organization.class).byMap(map).page(pageSize, pageIndex);
        for (Organization org : result.getContent()) {
            org.setDeviceMac(null);
            org.setDevicePassword(null);
        }
        return result;
    }

    public Organization findById(String id) {
        return new Finder<>(Organization.class).byId(id);
    }

    public Organization getByAccountId(String accountId) {
        return new Finder<>(Organization.class).byField("accountId", accountId).first();
    }

    public List<Organization> getOrgList() {
        List<Organization> list = new Finder<>(Organization.class).list();
        for (Organization org : list) {
            org.setDeviceMac(null);
            org.setDevicePassword(null);
        }
        return list;
    }

    //机构类型
    public boolean addType(Map map) {
        OrganizationType orgType = new OrganizationType();
        orgType.add(map);
        return true;
    }

    public boolean modifyType(String id, Map map) {
        OrganizationType orgType = new Finder<>(OrganizationType.class)
            .byId(id);
        orgType.modify(map);
        return true;
    }

    public boolean deleteType(String id) {
        OrganizationType orgType = new Finder<>(OrganizationType.class)
            .byId(id);
        orgType.delete();
        return true;
    }

    public List<OrganizationType> getTypeList() {
        return new Finder<>(OrganizationType.class).list();
    }

    public Organization getCurOrg() {
        AuthInfo authInfo = UserUtils.getCurrentUser();
        Organization org = new Finder<>(Organization.class)
            .byField("accountId", authInfo.getUserid()).first();
        if (org == null) throw new DomainException("机构不存在");
        return org;
    }

    public boolean modifyCustomInfo(Map map) {
        Organization org = getCurOrg();
        org.modifyCustomInfo(map);
        return true;
    }
}
